﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraPrinting;
using System.Data;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Base;
using System.Drawing;
using DevExpress.XtraEditors.Repository;
using DevExpress.XtraEditors.ViewInfo;
using DevExpress.XtraEditors.Drawing;
using System.IO;


namespace BellAssistant.Common.CommonHelper
{
    public class GridViewHelper
    {
        #region 绘制提示词
        /// <summary>
        /// 未查询到任何数据时，提示词。
        /// </summary>
        /// <param name="gridView1"></param>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void DrawEmptyForeground(GridView gridView1, object sender, CustomDrawEventArgs e)
        {
            ColumnView columnView = sender as ColumnView;
            BindingSource bindingSource = gridView1.DataSource as BindingSource;
            if (bindingSource == null || bindingSource.Count == 0)
            {
                string s = "未查询到任何数据！";
                Font f = new Font("宋体", 12, FontStyle.Regular);
                Rectangle r = new Rectangle(e.Bounds.Left + 35, e.Bounds.Top + 35, e.Bounds.Right - 5, e.Bounds.Height - 5);
                e.Graphics.DrawString(s, f, Brushes.Red, r);
            }
        }
        #endregion

        #region 绘制CheckBox
        /// <summary>
        /// 根据列FieldName为列头绘制CheckBox
        /// </summary>
        /// <param name="gridView1">GridView</param>
        /// <param name="checkItem">RepositoryItemCheckEdit</param>
        /// <param name="fieldName">需要绘制Checkbox的列名</param>
        /// <param name="e">ColumnHeaderCustomDrawEventArgs</param>
        public static void DrawHeaderCheckBox(GridView gridView1, RepositoryItemCheckEdit checkItem, string fieldName, ColumnHeaderCustomDrawEventArgs e)
        {
            if (e.Column != null && e.Column.FieldName.Equals(fieldName))
            {
                e.Info.InnerElements.Clear();
                e.Painter.DrawObject(e.Info);
                DrawCheckBox(checkItem, e.Graphics, e.Bounds, GetCheckedCount(gridView1, fieldName) == gridView1.DataRowCount);
                e.Handled = true;
            }
        }
        private static void DrawCheckBox(RepositoryItemCheckEdit checkItem, Graphics g, Rectangle r, bool Checked)
        {
            CheckEditViewInfo info;
            CheckEditPainter painter;
            ControlGraphicsInfoArgs args;
            info = checkItem.CreateViewInfo() as CheckEditViewInfo;
            painter = checkItem.CreatePainter() as CheckEditPainter;
            info.EditValue = Checked;

            info.Bounds = r;
            info.PaintAppearance.ForeColor = Color.Black;
            info.CalcViewInfo(g);
            args = new ControlGraphicsInfoArgs(info, new DevExpress.Utils.Drawing.GraphicsCache(g), r);
            painter.Draw(args);
            args.Cache.Dispose();
        }
        private static int GetCheckedCount(GridView view, string filedName)
        {
            int count = 0;
            for (int i = 0; i < view.DataRowCount; i++)
            {
                object cellValue = view.GetRowCellValue(i, view.Columns[filedName]);
                if (cellValue == null)
                    continue;
                if (string.IsNullOrEmpty(cellValue.ToString().Trim()))
                    continue;
                bool checkStatus = false;
                if (bool.TryParse(cellValue.ToString(), out checkStatus))
                {
                    if (checkStatus)
                        count++;
                }
            }
            return count;
        }
        /// <summary>
        /// 根据列Index为列头绘制CheckBox
        /// </summary>
        /// <param name="gridView1">GridView</param>
        /// <param name="checkItem">RepositoryItemCheckEdit</param>
        /// <param name="fieldName">需要绘制Checkbox的列名</param>
        /// <param name="e">ColumnHeaderCustomDrawEventArgs</param>
        public static void DrawHeaderCheckBox(GridView gridView1, RepositoryItemCheckEdit checkItem, int columnIndex, ColumnHeaderCustomDrawEventArgs e)
        {
            if (e.Column != null && e.Column.AbsoluteIndex == columnIndex)
            {
                e.Info.InnerElements.Clear();
                e.Painter.DrawObject(e.Info);
                DrawCheckBox(checkItem, e.Graphics, e.Bounds, GetCheckedCount(gridView1, columnIndex) == gridView1.DataRowCount);
                e.Handled = true;
            }
        }
        private static int GetCheckedCount(GridView view, int columnIndex)
        {
            int count = 0;
            for (int i = 0; i < view.DataRowCount; i++)
            {
                object cellValue = view.GetRowCellValue(i, view.Columns[columnIndex]);
                if (cellValue == null)
                    continue;
                if (string.IsNullOrEmpty(cellValue.ToString().Trim()))
                    continue;
                bool checkStatus = false;
                if (bool.TryParse(cellValue.ToString(), out checkStatus))
                {
                    if (checkStatus)
                        count++;
                }
            }
            return count;
        }
        #endregion

        #region 绘制行号
        /// <summary>
        /// 绘制GridView行号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public static void DrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
        {
            e.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far;
            if (e.Info.IsRowIndicator)
            {
                if (e.RowHandle >= 0)
                {
                    e.Info.DisplayText = (e.RowHandle + 1).ToString();
                }
                else if (e.RowHandle < 0 && e.RowHandle > -1000)
                {
                    e.Info.Appearance.BackColor = System.Drawing.Color.AntiqueWhite;
                    e.Info.DisplayText = e.RowHandle.ToString();
                }
            }

            //IndicatorObjectInfoArgs info = e.Info;
            //if (info == null || !info.IsRowIndicator || e.RowHandle < 0)
            //    return;
            //info.Appearance.TextOptions.HAlignment = HorzAlignment.Center;
            //info.DisplayText = (e.RowHandle + 1).ToString();
        }
        #endregion

        /// <summary>
        /// 填充数据
        /// </summary>
        /// <param name="gridControl1"></param>
        /// <param name="gridView1"></param>
        /// <param name="entityList"></param>
        public static void FillPageData(GridControl gridControl1, GridView gridView1, object entityList)
        {
            try
            {
                gridControl1.DataSource = entityList;
                //gridControl1.RefreshDataSource();
                gridView1.BestFitColumns();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 导出GridView的数据到Excel
        /// </summary>
        /// <param name="gridView1">GridView</param>
        /// <param name="dt">DataTable</param>
        public static void ExportToExcel(GridView gridView1, DataTable dt = null)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = FilterHelper.EXCEL_SAVE_FILTER;
            sfd.RestoreDirectory = true;
            if (sfd.ShowDialog() == DialogResult.OK)
            {
                string fileName = sfd.FileName;
                string ext = Path.GetExtension(fileName).ToLower(); //保存EXCEL文件选择的格式后缀
                XlsxExportOptions optionXlsx = new XlsxExportOptions(TextExportMode.Text, false);
                XlsExportOptions optionXls = new XlsExportOptions(TextExportMode.Text, false);

                if (dt == null)//使用DEV导出
                {
                    if (ext == ".xls")
                        gridView1.ExportToXls(fileName, optionXls);
                    else
                        gridView1.ExportToXlsx(fileName, optionXlsx);
                }
                else//使用NOPI导出
                {
                    ExcelNPOIHelper.DataTableToExcel(dt, fileName);
                }
            }
        }
    }
}
